﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Adex;
using MediaMonitor.Common;
using System.Data;

namespace MediaMonitor.Admin
{
    public partial class Country_Mgmt : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }

            btnSave.Visible = lstMediaType.Enabled = Utility.ToInt(lstCountry.SelectedValue) > 0;
            lblMsg.Text = "";
        }

        protected void lstCountry_DataBound(object sender, EventArgs e)
        {

            lstCountry.Items.Insert(0, new ListItem("- SELECT -", "0"));

        }
        protected void lstCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Adex.CommercialLog
            DataTable dt = Adex.CountryMedium.Query().WHERE("CountryID", lstCountry.SelectedValue).ExecuteDataSet().Tables[0];

            foreach (ListItem itm in lstMediaType.Items)
            {
                itm.Selected = false;
            }

            foreach (DataRow dr in dt.Rows)
            {
                foreach (ListItem itm in lstMediaType.Items)
                {

                    if (itm.Value == dr["MediaTypeCode"].ToString())
                    {
                        itm.Selected = true;
                    }

                }
            }


        }

        protected void btnSave_Clicked(object sender, EventArgs e)
        {


            byte countryID = Utility.ToByte(lstCountry.SelectedValue);
            //delete all existing country's media types.

            foreach (ListItem itm in lstMediaType.Items)
            {

                if (itm.Selected)
                {

                    if (CountryMedium.Query().WHERE("CountryID", countryID).AND("MediaTypeCode", itm.Value).GetCount("CountryID") == 0)
                    {
                        CountryMedium cm = new CountryMedium();
                        cm.CountryID = countryID;
                        cm.MediaTypeCode = Utility.ToInt(itm.Value);
                        cm.Save();
                    }
                }
                else
                {

                    SubSonic.DeleteQuery delSql = new SubSonic.DeleteQuery(Adex.CountryMedium.Schema.TableName);

                    delSql.WHERE("CountryID", countryID).AND("MediaTypeCode", itm.Value).GetCount("CountryID");
                    delSql.Execute();
                }

            }

            lblMsg.Text = "Selected Country & Media Combination saved successfully.";


        }
    }
}